from flask import Flask, request, redirect, url_for, flash
import pymysql
import os

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于保持会话安全

# 数据库配置
server = "mysql.metropolia.fi"
login = "pegahk"
password = "3392796255"
database = "pegahk"

# 连接到数据库
def get_db_connection():
    connection = pymysql.connect(
        host=server,
        user=login,
        password=password,
        db=database,
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor
    )
    return connection

@app.route('/submit', methods=['POST'])
def submit():
    if request.method == 'POST':
        cate = request.form.get('cate')
        name = request.form['Name']
        desc = request.form['Desc']
        size = request.form['Size']
        price = request.form['Price']
        price_id = request.form['P_cate']
        image = request.files['image']
        key = request.form['key']

        # 保存图片
        if image:
            image.save(os.path.join("pic", image.filename))

        # 插入数据库
        conn = get_db_connection()
        cursor = conn.cursor()
        sql = """
        INSERT INTO `items` (`item_cat`, `Name`, `Description`, `Size`, `Price`, `image`, `price_id`, `Search_key`) 
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
        """
        values = (cate, name, desc, size, price, image.filename, price_id, key)
        cursor.execute(sql, values)
        conn.commit()
        cursor.close()
        conn.close()

        flash('Product Has Been Inserted', 'success')
        return redirect(url_for('admin'))

@app.route('/admin')
def admin():
    return "Admin Page"

if __name__ == '__main__':
    app.run(debug=True)